package com.easyattendance.servlets;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.easyattendance.model.Section;
import com.easyattendance.model.User;
import com.easyattendance.nls.UseProperties;
import com.easyattendance.services.AddSectionService;
import com.easyattendance.services.LoginService;
import com.easyattendance.services.ValidationsService;
import com.easyattendance.util.SecurePassword;


@WebServlet(name = "AddSectionServlet", urlPatterns = { "/AddSectionServlet" })
public class AddSectionServlet extends HttpServlet {
	
	private static final long serialVersionUID = 7936685032631201979L;

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {  
    	response.setContentType("text/html;charset=UTF-8");
		 
		String actionType = request.getParameter("action_type");
		boolean dispatcherFlag = false;
		
		AddSectionService addSectionService = new AddSectionService();
		ValidationsService validationsService = new ValidationsService();
		
		if(actionType.equals("create")) {
			String sectionName = request.getParameter("section_name");
			String termStartDate = request.getParameter("term_start_date");
			String termEndDate = request.getParameter("term_end_date");
			String sectionEmail = request.getParameter("section_email");
	        String sectionPassword = request.getParameter("section_password");
	        String sectionRepassword = request.getParameter("section_repassword");
	        
	        
	        if(sectionName.isEmpty() || sectionEmail.isEmpty() || sectionPassword.isEmpty() || sectionRepassword.isEmpty() || termStartDate.isEmpty() || termEndDate.isEmpty()){
	        	request.setAttribute("null_values", "All * fields are required");
	        	dispatcherFlag = true;
	        }
	        else {
	        	String validateName = validationsService.validateName(sectionName);
		        String validateEmail = validationsService.validateEmailId(sectionEmail);
		        boolean validatePasswords = validationsService.validateBothPasswords(sectionPassword, sectionRepassword);
		        
		        if(validateName.equals("Correct")) {
		        	if(validateEmail.equals("Correct")) {
		        		if(validatePasswords) {
		        			String secret_key = UUID.randomUUID().toString();
		 	 	 	       
					        Date start_date=null,end_date=null;
					        java.sql.Date start_sql=null,end_sql=null;
					        try {
								 start_date=new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("term_start_date"));
								 start_sql=new java.sql.Date(start_date.getTime());
								 
								 end_date=new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("term_end_date"));
								 end_sql=new java.sql.Date(end_date.getTime());
					        } catch (ParseException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					        
					        
					        LoginService loginService = new LoginService();
					        int roleId=2;  // roleId is 2 for department
					        
					        /*ResourceBundle labels = ResourceBundle.getBundle("nls.Attendance");
					        int counter = Integer.parseInt(labels.getString("easyattendance.label.counter"));*/
					        
					        /*
					         * 
					         * while deleting dept from table remember to decrement counter from ./Attendance.properties file too
					         */
					        
					        Section newSection = new Section(sectionName, sectionEmail);
					        boolean res = addSectionService.ifAlreadyExists(newSection);
					        
					        boolean flag = loginService.ifAlreadyExists(sectionEmail);
					        String ID=null;
					        boolean result=false;
					        
					        if( !res) {
					        	if(!flag) {
					        		Properties labels = UseProperties.loadProperties("Attendance.properties");
					            	//labels = UseProperties.incrementSectionIdCounterValue(labels);
					            	ID = UseProperties.getSectionIdPrefix(labels)+addSectionService.getSectionIdValue();
					            	
					            	//User newUser = new User(ID,roleId,sectionPassword,sectionEmail,"1234",false,true);
					            	//newUser.setDept(dept); No need to add dept oject.. user_id reference is sufficient
					            	User newUser = new User(ID,roleId,SecurePassword.getHashValue(sectionPassword),sectionEmail,secret_key,false,true);
					            	loginService.addNewUser(newUser);
					            	
					            	if(!(start_date.equals("")) && !(end_date.equals("")))
					            	{
					            		Section section=new Section(ID,sectionName, sectionEmail,start_sql,end_sql);
					            		section.setUser(newUser);
					                    result = addSectionService.addSection(section);
					            	}
					            	else
					            	{
					            		Section section = new Section(ID,sectionName, sectionEmail);
					            		section.setUser(newUser);
					                    result = addSectionService.addSection(section);
					            	}
					            }
					        	else {
					        		Properties labels = UseProperties.loadProperties("Attendance.properties");
					        		labels = UseProperties.decrementSectionIdCounterValue(labels);
					        		//out.println("User already exists.. check emailID");
					        		request.setAttribute("user_exists", "User already exists.. check emailID.");
						        	dispatcherFlag = true;
					        	}
					        }
					        else {
					        	//out.println("Section already exists.. check emailID");
					        	request.setAttribute("section_exists", "Section already exists.. check emailID.");
					        	dispatcherFlag = true;
					        }
					        					       
							if (result) {
								//out.println("<h1>Section added Successfully</h1>");
								
								request.setAttribute("section_add_successfull", "Section added Successfully.");
					        	dispatcherFlag = true;
					        	
								addSectionService.SendMail(sectionEmail);
								//out.println("To login with new UserId and Password<a href=\"views/login.jsp\">Click here</a>");
							} else {
								Properties labels = UseProperties.loadProperties("Attendance.properties");
				        		labels = UseProperties.decrementSectionIdCounterValue(labels);
				        		request.setAttribute("section_add_not_successfull", "Section Not added.");
					        	dispatcherFlag = true;
				        		
								//out.println("<h1>Section not added successfully</h1>");
								//out.println("To try again<a href=\"views/admin/addSection.jsp\">Click here</a>");
							}	
		        		}
		        		else {
		        			request.setAttribute("validate_section_passwords", "Passwords do not match.");
				        	dispatcherFlag = true;
		        		}
		        	}
		        	else {
		        		request.setAttribute("validate_section_email", validateEmail);
			        	dispatcherFlag = true;
		        	}
		        }
		        else {
		        	request.setAttribute("validate_section_name", validateName);
		        	dispatcherFlag = true;
		        }
		        if(dispatcherFlag) {
		        	RequestDispatcher rd = request.getRequestDispatcher("views/admin/addSection.jsp");
			    	rd.forward(request, response);
		        }
	        }
		}
		else if(actionType.equals("update")) {
			int i = Integer.parseInt(request.getParameter("i_value"));
			dispatcherFlag = false;
			
			String sectionName = request.getParameter("section_name"+i);
	        String sectionEmail = request.getParameter("section_email"+i);
	        
	        Date start_date=null,end_date=null;
	        java.sql.Date start_sql=null,end_sql=null;
	        try {
				 start_date=new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("term_start_date"+i));
				 start_sql=new java.sql.Date(start_date.getTime());
				 
				 end_date=new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("term_end_date"+i));
				 end_sql=new java.sql.Date(end_date.getTime());
	        } catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        
	        Section section = addSectionService.getSectionBySectionEmail(sectionEmail);
	        section.setSection_name(sectionName);
	        section.setTerm_start_date(start_sql);
	       section.setTerm_end_date(end_sql);
	       boolean res = addSectionService.updateSection(section);
	       
	        if(res) {
	        	//out.println("Section updated successfully");
	        	request.setAttribute("section_update_successfull", "Section updated successfully.");
	        	dispatcherFlag = true;
	        }
	        else {
	        	//out.println("Section NOT updated successfully.. try again");
	        	request.setAttribute("section_update_not_successfull", "Section not updated.");
	        	dispatcherFlag = true;
	        }
	        if(dispatcherFlag) {
		        RequestDispatcher rd = request.getRequestDispatcher("views/admin/sectionSettings.jsp");
		    	rd.forward(request, response);
	        }
		}
		else if(actionType.equals("delete")) {
			int i = Integer.parseInt(request.getParameter("i_value"));
			String sectionEmail = request.getParameter("section_email"+i);
			//Section section = addSectionService.getSectionBySectionEmail(sectionEmail);
			dispatcherFlag = false;
			
			boolean res = addSectionService.deleteSection(sectionEmail);
			
			if(res){
				//out.println("Section deleted successfully");
				request.setAttribute("section_delete_successfull", "Section deleted successfully.");
	        	dispatcherFlag = true;
			}
			else {
				//out.println("Section CANNOT be deleted successfully");
				request.setAttribute("section_delete_not_successfull", "Section not deleted.");
	        	dispatcherFlag = true;
			}
			if(dispatcherFlag) {
				RequestDispatcher rd = request.getRequestDispatcher("views/admin/sectionSettings.jsp");
		    	rd.forward(request, response);
			}
		}
		else {
			//out.println("Invalid selection.. go back and try again");
			request.setAttribute("section_invalid_selection", "Invalid selection.. go back and try again.");
			RequestDispatcher rd = request.getRequestDispatcher("views/admin/sectionSettings.jsp");
	    	rd.forward(request, response);
		}
    }

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>
}
